package com.alu4r.atcrowdfunding.manager.controller;

import com.alu4r.atcrowdfunding.bean.Advertisement;
import com.alu4r.atcrowdfunding.bean.User;
import com.alu4r.atcrowdfunding.manager.service.AdvertService;
import com.alu4r.atcrowdfunding.util.AjaxResult;
import com.alu4r.atcrowdfunding.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.UUID;

@Controller
@RequestMapping("/advert")
public class AdvertController {

    @Autowired
    AdvertService advertService;

    @RequestMapping("/doAdd")
    public String doAdd(HttpServletRequest request, Advertisement advertisement , HttpSession session) {
        AjaxResult result = new AjaxResult();

        try {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)request;

            MultipartFile mfile = mreq.getFile("advpic");

            String name = mfile.getOriginalFilename();//java.jpg
            String extname = name.substring(name.lastIndexOf(".")); // .jpg

            String iconpath = UUID.randomUUID().toString()+extname; //232243343.jpg

            ServletContext servletContext = session.getServletContext();
            String realpath = servletContext.getRealPath("/pics");

            String path =realpath+ "\\adv\\"+iconpath;


            mfile.transferTo(new File(path));

            User user = (User)session.getAttribute(Constant.LOGIN_USER);
            System.out.println("&&&&&&&&&&&&&&&&&&&&&"+advertisement.toString());
            advertisement.setUserid(user.getId());
            advertisement.setStatus("1");
            advertisement.setIconpath(iconpath);

            int count = advertService.insertAdvert(advertisement);
            result.setSuccess(count==1);
        } catch ( Exception e ) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "advert/index";
    }
}
